<template>
  <div class="app-container">
    <el-progress v-if="isShowProgress" :percentage="excelUploadPercent" type="line" color="red" class="excel-upload-progress"/>
    <div class="filter-container">
      <el-input v-model="searchObj.data.key" size="medium" placeholder="字典键" class="global-search-box"/>
      <el-input v-model="searchObj.data.value" size="medium" placeholder="字典值" class="global-search-box"/>
      <el-select v-model="searchObj.data.group_id" clearable placeholder="业务模块" size="medium" class="global-search-box">
        <el-option
          v-for="operation in operations"
          :key="operation.id"
          :label="operation.name"
          :value="operation.id"/>
      </el-select>
      <el-button type="primary" size="medium" icon="el-icon-search" @click="getDataDics()">搜索</el-button>
      <el-button type="primary" size="medium" @click="reset()">重置</el-button>
      <span class="filter-container-right">
        <el-button type="primary" size="medium" icon="el-icon-download" @click="downloadExcelShow">选择模块</el-button>
        <el-upload
          v-permission= "{ permissionCode: 'dict:import' }"
          :on-success="handleSuccess"
          :on-progress="uploadProcess"
          :before-upload="beforeUpload"
          :action= "uploadAction"
          :headers="{ jwtToken: jwtToken }"
          :show-file-list="false"
          name="template"
          class="global-upload"
        >
          <el-button size="medium" type="primary" icon="el-icon-upload2">批量导入</el-button>
        </el-upload>
        <el-button v-permission= "{ permissionCode: 'dict:add' }" type="primary" size="medium" icon="el-icon-plus" @click="addDictionary">新增</el-button>
        <el-button v-permission= "{ permissionCode: 'dict:delete' }" type="danger" size="medium" icon="el-icon-close" @click="deleteDics">删除</el-button>
      </span>
    </div>
    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      fit
      border
      highlight-current-row
      @selection-change="handleSelectChange">
      <el-table-column type="selection" width="40"/>
      <el-table-column align="center" label="字典键" prop="key" min-width="100"/>
      <el-table-column align="center" label="字典值" prop="value" min-width="200"/>
      <el-table-column align="center" label="业务模块" prop="group_name" min-width="100"/>
      <el-table-column align="center" label="创建人" prop="create_user" min-width="100"/>
      <el-table-column align="center" label="最新修改人" prop="last_modify_user" min-width="100"/>
      <el-table-column align="center" label="创建日期" prop="create_date" min-width="160"/>
      <el-table-column align="center" label="最近更新日期" prop="modify_date" min-width="160"/>
      <el-table-column align="center" label="描述" prop="description" min-width="200"/>
      <el-table-column align="center" label="操作" min-width="200">
        <template slot-scope="scope">
          <el-button v-permission= "{ permissionCode: 'dict:update' }" type="primary" size="mini" icon="el-icon-edit" @click="editDic(scope.row)">修改</el-button>
          <el-button v-permission= "{ permissionCode: 'dict:delete' }" type="danger" size="mini" icon="el-icon-delete" @click="deleteDic(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog :visible.sync="groupFormVisible" title="选择下载模块" width="400px">
      <el-select v-model="group_name" size="medium" style="width: 300px">
        <el-option
          v-for="operation in operations"
          :key="operation.id"
          :label="operation.name"
          :value="operation.name"/>
      </el-select>
      <div slot="footer" class="dialog-footer">
        <el-button @click="groupFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="downloadExcel">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog :title=" isEdit ? '编辑资源' : '新增资源'" :visible.sync="FormVisible" width="600px">
      <el-form ref="ruleForm" :model="dicForm" :rules="rules" >
        <el-form-item :label-width="formLabelWidth" label="字典编码">
          <el-input v-model="dicForm.code" auto-complete="off"/>
        </el-form-item>
        <el-form-item :label-width="formLabelWidth" label="字典键" prop="key">
          <el-input v-model="dicForm.key" auto-complete="off"/>
        </el-form-item>
        <el-form-item :label-width="formLabelWidth" label="字典值" prop="value">
          <el-input v-model="dicForm.value" auto-complete="off"/>
        </el-form-item>
        <el-form-item :label-width="formLabelWidth" label="业务模块" prop="group_id">
          <el-select v-model="dicForm.group_id" size="medium">
            <el-option
              v-for="operation in operations"
              :key="operation.id"
              :label="operation.name"
              :value="operation.id"/>
          </el-select>
        </el-form-item>
        <el-form-item :label-width="formLabelWidth" label="描述">
          <el-input v-model="dicForm.description" type="textarea" auto-complete="off"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelAdd()">取 消</el-button>
        <el-button type="primary" @click="isEdit ? confirmEditDictionary('ruleForm') : confirmAddDictionary('ruleForm')">确 定</el-button>
      </div>
    </el-dialog>
    <div class="global-paging">
      <el-pagination
        :page-size="10"
        :total="total"
        :page-sizes="[10, 20, 40]"
        background
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"/>
    </div>
  </div>
</template>

<script>
import commonApi from '@/api/commonApi'
import { getToken } from '@/utils/auth'
export default {
  name: 'DataDictionary',
  data() {
    return {
      te: null,
      excelUploadPercent: 0,
      isShowProgress: false,
      FormVisible: false,
      groupFormVisible: false,
      group_name: '',
      uploadAction: null,
      jwtToken: null,
      isEdit: false,
      list: null,
      listLoading: false,
      total: null,
      rules: {
        key: [
          { required: true, message: '请输入字典键', trigger: 'blur' }
        ],
        value: [
          { required: true, message: '请输入字典值', trigger: 'blur' }
        ],
        group_id: [
          { required: true, message: '请选择业务模块', trigger: 'change' }
        ]
      },
      delDicIds: [],
      formLabelWidth: '120px',
      searchObj: {
        currentNo: 1,
        pageSize: 10,
        data: {
          key: '',
          value: null,
          group_id: null
        }
      },
      dicForm: {
        key: null,
        value: null,
        code: null,
        group_id: null,
        description: null
      },
      operations: [],
      copyDicForm: {} // 修改取消时使用
    }
  },
  created() {
    this.getDataDics()
    this.getOperations()
    this.uploadAction = `${process.env.BASE_API}/dict/uploadTemplate`
    this.jwtToken = getToken()
  },
  methods: {
    downloadExcelShow() {
      this.groupFormVisible = true
    },
    downloadExcel() {
      window.location.href = process.env.BASE_API + '/dict/downloadTemplate/common'
      this.groupFormVisible = false
    },
    uploadProcess(event, file, fileList) {
      this.excelUploadPercent = parseInt(file.percentage.toFixed(0))
    },
    beforeUpload() {
      this.isShowProgress = true
    },
    handleSuccess(response) {
      if (response.code === 1) {
        this.$message({
          type: 'success',
          message: '数据字典导入成功'
        })
        this.getDataDics()
      }
      if (response.code === 0) {
        this.$alert(response.msg, '提示', {
          confirmButtonText: '确定',
          type: 'error'
        })
      }
      this.isShowProgress = false
    },
    handleCurrentChange(val) {
      this.searchObj.currentNo = val
      this.getDataDics()
    },
    handleSizeChange(val) {
      this.searchObj.pageSize = val
      this.getDataDics()
    },
    getDataDics() {
      this.listLoading = true
      commonApi('/dict/queryDict', 'post', this.searchObj).then(response => {
        if (response.code === 1) {
          this.list = response.data.rows
          this.total = response.data.total
          this.listLoading = false
        }
      }).catch((response) => {
        if (response.code === 403) {
          this.$alert('没有权限访问页面，请联系管理员', '提示', {
            confirmButtonText: '确定',
            type: 'error',
            callback: () => {
              this.$router.go(-1)
            }
          })
        }
        this.listLoading = false
      })
    },
    getOperations() {
      commonApi('/dict/queryGroup', 'get').then(response => {
        if (response.code === 1) {
          this.operations = response.data
        }
      })
    },
    reset() {
      for (const index in this.searchObj.data) {
        this.searchObj.data[index] = null
      }
      this.getDataDics()
    },
    handleSelectChange(valArr) {
      this.delDicIds = []
      for (let i = 0; i < valArr.length; i++) {
        this.delDicIds.push(valArr[i].id)
      }
    },
    addDictionary() {
      this.isEdit = false
      this.dicForm = {}
      this.FormVisible = true
    },
    confirmAddDictionary(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.FormVisible = false
          this.listLoading = true
          commonApi('/dict/addDict', 'post', this.dicForm).then(response => {
            if (response.code === 1) {
              this.cancelAdd()
              this.listLoading = false
              this.getDataDics()
            }
          }).catch(() => {
            this.listLoading = false
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    cancelAdd() {
      this.$refs['ruleForm'].resetFields()
      this.FormVisible = false
      if (!this.isEdit) {
        this.dicForm = {}
      } else {
        this.dicForm = this.copyDicForm
      }
    },
    deleteDic(row) {
      this.$confirm(`确定要删除数据字典：${row.value} ?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.delDicIds.push(row.id)
        this.deleteDicsInterim()
      }).catch(() => {
      })
    },
    deleteDics() {
      if (this.delDicIds.length === 0) {
        this.$message({
          message: '请选择需要删除数据字典 ！',
          type: 'error'
        })
        return
      }
      this.$confirm(`确定要批量数据字典 ?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'error'
      }).then(() => {
        this.deleteDicsInterim()
      }).catch(() => {
      })
    },
    deleteDicsInterim() {
      this.listLoading = true
      commonApi('/dict/deleteDict', 'post', this.delDicIds).then(response => {
        if (response.code === 1) {
          this.$message({
            message: '数据字典删除完成',
            type: 'success'
          })
          this.listLoading = false
          this.delDicIds = []
          this.getDataDics()
        }
      }).catch(() => {
        this.listLoading = false
      })
    },
    editDic(row = {}) {
      this.FormVisible = true
      this.isEdit = true
      this.dicForm = row
      console.log(this.dicForm)
      this.copyDicForm = row
    },
    confirmEditDictionary(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.FormVisible = false
          this.listLoading = true
          commonApi('/dict/updateDict', 'post', this.dicForm).then(response => {
            if (response.code === 1) {
              this.cancelAdd()
              this.listLoading = false
              this.getDataDics()
            }
          }).catch(() => {
            this.listLoading = false
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    }
  }
}
</script>
<style lang="scss">
  .excel-upload-progress{
    margin-top: -16px;
  }
</style>
